Nosana: OllamaでOpenAI GPT-OSS:20Bを使用する

最新のOpenAIオープンウェイトモデルgpt-oss:20bを、分散型モデル推論を可能にするNosanaの分散型GPUネットワークで実行するチュートリアルへようこそ。このセットアップは、ローカルマシンの性能を超えるコンピューティングパワーが必要な場合に、高価なハードウェアを自分で管理する手間なしに利用できるため優れています。

Nosanaで実際にジョブを起動し、base_urlを取得する方法を学びたいですか? 以下のリソースを参照してください:

以下の内容をカバーします:

  • 環境のセットアップ。
  • リモートNosana Base URLへの接続。
  • gpt-oss:20bモデルのプルと対話。
  • 基本的なテキスト生成、ストリーミング、チャット。
  • 関数呼び出しの簡単な例。

1. セットアップとインストール

まず、必要なPythonライブラリをインストールする必要があります。Ollamaサーバーとの通信にはollamaを、環境変数を安全に管理するにはpython-dotenvを使用します。

%pip install ollama python-dotenv

環境変数

リモートサーバーに接続するには、Ollamaクライアントにそのアドレスを伝える必要があります。これを.envファイルに保存し、コードから分離して構成をきれいに保ちます。

このノートブックと同じディレクトリに.envという名前のファイルを作成し、リモートサーバーのURLを追加してください。Nosanaを使用している場合、これは一意のNOSANA_BASE_URLになります。

.envファイルは以下のようになります:

OLLAMA_HOST=your_nosana_base_url_here

2. 設定の読み込みと接続

では、.envファイルから環境変数を読み込みましょう。ollama-pythonライブラリは賢く、設定したOLLAMA_HOST変数を自動的に使用します。明確にするため、クライアントを作成して明示的にホストを渡す方法も示します。

import os
from dotenv import load_dotenv
import ollama
from IPython.display import display, Markdown

# Load environment variables from .env file
load_dotenv()

# Get the remote server URL from environment variables
ollama_host = os.getenv("NOSANA_BASE_URL")

def short_link(link):
    if link and len(link) > 10:
        return link[:20] + '...' + link[-20:]
    return link

if not ollama_host:
    print("OLLAMA_HOST environment variable not found!")
    print("Please create a .env file and add your remote server URL.")
else:
    print(f"Connecting to remote Ollama server at: {short_link(ollama_host)}")

# You can create a client explicitly, which is good practice
client = ollama.Client(host=ollama_host)
Connecting to remote Ollama server at: https://4w9w89qshprb...node.k8s.prd.nos.ci/

3. モデルとの対話

接続が確立したら、gpt-oss:20bモデルとの対話を開始できます。モデルがリモートサーバーにまだない場合、Ollamaは初回実行時に自動的にダウンロードします。明示的にプルすることもできます。

model_name = 'gpt-oss:20b'

try:
    display(Markdown(f"Pulling the '{model_name}' model. This may take a while..."))
    client.pull(model_name)
    display(Markdown("Model pulled successfully!"))
except Exception as e:
    display(Markdown(f"Error: {e}"))

Pulling the 'gpt-oss:20b' model. This may take a while...

Model pulled successfully!

基本的な生成

簡単なテキスト生成リクエストから始めましょう。

response = client.generate(
    model=model_name,
    prompt='Explain the concept of a Large Language Model in one sentence.'
)

print(response['response'])
A Large Language Model is an AI system trained on vast text data that learns statistical patterns of language so it can generate, translate, or understand text in a way that mimics human style.

ストリーミング応答

よりインタラクティブなアプリケーションでは、応答が生成されるにつれてストリーミングできます。これは、リアルタイムのタイピング効果を表示するのに最適です。

stream = client.generate(
    model=model_name,
    prompt='Write a short story about a robot who discovers music in 50 words.',
    stream=True
)

for chunk in stream:
    print(chunk['response'], end='', flush=True)
Steel heart, dormant in the workshop, scanned old vinyl. A crackling needle whispered rhythm. The robot’s circuits sparked, translating harmonies into code. With each chord, gears wavered, emotions blooming. It recorded melodies, breathing life into metal. Music, the universe’s pulse, filled his void, and he sang for eternal resonance always.

チャットインターフェース

chatメソッドは会話的な対話向けに設計されており、モデルが会話のコンテキストを記憶します。

messages = [
    {
        'role': 'user',
        'content': 'What is the most important programming language for AI development? Explain in 50 words.'
    }
]

chat_response = client.chat(model=model_name, messages=messages)
display(Markdown(chat_response['message']['content']))

Python remains the cornerstone of AI development, offering extensive libraries (TensorFlow, PyTorch, Scikit‑learn), a clear syntax, and a massive community. Its rapid prototyping, readability, and cross‑platform compatibility make researchers and engineers quickly build, test, and deploy models, keeping AI accessible to all developers in industry and academia alike and beyond.

4. 高度な機能: 関数呼び出し

gpt-ossモデルは関数呼び出し(またはツール使用)に優れた能力を持っています。これにより、モデルは、外部情報を取得したりアクションを実行したりするために、コードで定義した関数の呼び出しをリクエストできます。

以下は、天気を取得するツールを定義する簡単な例です。

import json
import requests

def get_current_weather(city: str):
    """Get the current weather in a given city using Open-Meteo API"""
    # Geocoding to get latitude and longitude
    geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1"
    geo_resp = requests.get(geo_url)
    geo_data = geo_resp.json()
    if not geo_data.get("results"):
        return json.dumps({"city": city, "temperature": "unknown", "unit": "celsius"})
    lat = geo_data["results"][0]["latitude"]
    lon = geo_data["results"][0]["longitude"]
    # Get current weather
    weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t_weather=true"
    weather_resp = requests.get(weather_url)
    weather_data = weather_resp.json()
    temp = weather_data.get("current_weather", {}).get("temperature")
    if temp is None:
        return json.dumps({"city": city, "temperature": "unknown", "unit": "celsius"})
    return json.dumps({"city": city, "temperature": temp, "unit": "celsius"})

tools = [
    {
        'type': 'function',
        'function': {
            'name': 'get_current_weather',
            'description': 'Get the current weather in a given city',
            'parameters': {
                'type': 'object',
                'properties': {
                    'city': {
                        'type': 'string',
                        'description': 'The city, e.g., San Francisco',
                    },
                },
                'required': ['city'],
            },
        },
    },
]

messages = [{'role': 'user', 'content': 'What is the weather like in Singapore?'}]

# First, let the model decide which tool to call
response = client.chat(
    model=model_name,
    messages=messages,
    tools=tools,
)

messages.append(response['message'])

# Then, execute the tool and send the result back to the model
if response['message'].get('tool_calls'):
    tool_call = response['message']['tool_calls'][0]
    function_name = tool_call['function']['name']
    function_args = tool_call['function']['arguments']  # Already a dict
    
    # Call the function
    function_response = get_current_weather(city=function_args.get('city'))
    
    messages.append(
        {
            'role': 'tool',
            'content': function_response,
        }
    )
    
    # Get the final response from the model
    final_response = client.chat(model=model_name, messages=messages)
    print(final_response['message']['content'])
Singapore’s weather is typically hot and humid year‐round. Right now the temperature is about **27 °C** (≈80 °F). It’s in the range of 25–31 °C most days, with high humidity and a chance of brief showers, especially during the monsoon seasons.

まとめ

おめでとうございます!🎉 リモートOllamaサーバーへの接続、gpt-oss:20bモデルとの対話、さらには関数呼び出し機能も探索できました。

このリモートセットアップにより、どこからでも強力なモデルを利用でき、机の上にスーパーコンピュータを置く必要がありません。ここから、複雑なアプリケーションを構築したり、異なるモデルを試したり、特定のニーズに合わせてモデルを微調整したりできます。


より多くのモデルを探索し、AIアプリにパワーを与える準備はできていますか?

👉 Nosana.comを訪れて、より多くのモデルを発見し、AIプロジェクトを加速させましょう!